// DX9 Tank Game - Main Entry
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <string>
#include <vector>
#include "Terrain.h"
#include "StaticObject.h"
#include "MovingObstacle.h"
#include "Camera.h"
#include "NPCManager.h"
#include "PlayerTank.h"
#include "Projectile.h"
#include "UIRenderer.h"

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")

// 全局变量
LPDIRECT3D9 g_pD3D = NULL;
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
HWND g_hWnd = NULL;

const int SCREEN_WIDTH = 1280;
const int SCREEN_HEIGHT = 720;

// 游戏对象
Terrain* g_pTerrain = NULL;
Camera* g_pCamera = NULL;
std::vector<StaticObject*> g_staticObjects;
std::vector<MovingObstacle*> g_movingObstacles;
std::vector<GameObject*> g_staticObjsForCollision;  // 用于碰撞检测的GameObject*向量（全局生命周期）
std::vector<GameObject*> g_allObstacles;  // 全局障碍物列表（静态+运动），供玩家坦克使用
NPCManager* g_pNPCManager = NULL;
PlayerTank* g_pPlayerTank = NULL;  // Stage 3: Player tank
std::vector<Projectile*> g_projectiles;  // Active projectiles
UIRenderer* g_pUIRenderer = NULL;  // UI renderer for crosshair, health bar, etc.
float g_damageIndicatorIntensity = 0.0f;  // For red screen flash when damaged

// 前向声明
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
bool InitD3D(HWND hWnd);
bool InitGame();
void CleanupD3D();
void CleanupGame();
void SetupLighting();
void Render();
void Update(float deltaTime);

// Windows消息处理
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE)
            PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

// 初始化D3D
bool InitD3D(HWND hWnd)
{
    // 创建D3D对象
    g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
    if (!g_pD3D)
        return false;

    // 设置D3D参数
    D3DPRESENT_PARAMETERS d3dpp = {};
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    d3dpp.BackBufferWidth = SCREEN_WIDTH;
    d3dpp.BackBufferHeight = SCREEN_HEIGHT;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
    d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

    // 创建D3D设备
    HRESULT hr = g_pD3D->CreateDevice(
        D3DADAPTER_DEFAULT,
        D3DDEVTYPE_HAL,
        hWnd,
        D3DCREATE_HARDWARE_VERTEXPROCESSING,
        &d3dpp,
        &g_pd3dDevice
    );

    if (FAILED(hr))
        return false;

    // 设置渲染状态
    g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE);
    g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
    g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
    g_pd3dDevice->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(50, 50, 50));

    // 禁用 Alpha 混合（确保地形完全不透明）
    g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);

    // 开启深度写入（确保地形正确遮挡）
    g_pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);

    // 设置深度测试模式
    g_pd3dDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);

    return true;
}

// 初始化游戏对象
bool InitGame()
{
    // 创建地形 (1000x1000)
    OutputDebugStringA("开始创建地形...\n");
    g_pTerrain = new Terrain();
    if (!g_pTerrain->Initialize(g_pd3dDevice, 1001, 1001))
    {
        OutputDebugStringA("地形初始化失败！\n");
        return false;
    }
    OutputDebugStringA("地形创建成功\n");

    // 创建相机 - 侧面视角更能看清物体是否贴地
    g_pCamera = new Camera();
    g_pCamera->SetPosition(D3DXVECTOR3(500.0f, 50.0f, 200.0f));  // 降低高度，侧面视角
    g_pCamera->SetTarget(D3DXVECTOR3(500.0f, 0.0f, 500.0f));  // 看向场景中心
    g_pCamera->SetPerspective(D3DX_PI / 4.0f, (float)SCREEN_WIDTH / SCREEN_HEIGHT, 0.1f, 10000.0f);

    // 创建20个固定障碍物
    for (int i = 0; i < 20; i++)
    {
        StaticObject* obj = new StaticObject();

        // 随机选择形状
        ObjectShape shape = (ObjectShape)(rand() % 3);
        D3DXVECTOR3 size;

        switch (shape)
        {
        case SHAPE_BOX:
            size = D3DXVECTOR3(10.0f + rand() % 20, 10.0f + rand() % 20, 10.0f + rand() % 20);
            break;
        case SHAPE_CYLINDER:
            size = D3DXVECTOR3(5.0f + rand() % 10, 15.0f + rand() % 15, 0.0f);
            break;
        case SHAPE_SPHERE:
            size = D3DXVECTOR3(5.0f + rand() % 10, 0.0f, 0.0f);
            break;
        }

        if (!obj->Initialize(g_pd3dDevice, shape, size))
        {
            delete obj;
            continue;
        }

        // 随机位置 (避开边缘)
        float x = 100.0f + (rand() % 800);
        float z = 100.0f + (rand() % 800);
        float terrainHeight = g_pTerrain->GetHeight(x, z);

        // 计算物体底部贴地的Y坐标
        float y = terrainHeight;
        switch (shape)
        {
        case SHAPE_BOX:
            y += size.y * 0.5f;  // 立方体中心在高度的一半
            break;
        case SHAPE_CYLINDER:
            y += size.y * 0.5f;  // 圆柱体中心在高度的一半
            break;
        case SHAPE_SPHERE:
            y += size.x;  // 球体中心在半径高度（size.x是半径）
            break;
        }

        obj->SetPosition(D3DXVECTOR3(x, y, z));

        // DEBUG: Show first object position in window title
        if (i == 0)
        {
            // Also check terrain vertex actual Y coordinate
            float actualTerrainY = g_pTerrain->GetHeight(x, z);
            wchar_t title[256];
            swprintf_s(title, L"Obj: T=%.2f, Y=%.2f, Size=%.2f, Bottom=%.2f",
                terrainHeight, y, size.y, y - size.y*0.5f);
            SetWindowText(g_hWnd, title);
        }

        // 随机颜色
        BYTE r = 100 + rand() % 156;
        BYTE g = 100 + rand() % 156;
        BYTE b = 100 + rand() % 156;
        obj->SetColor(D3DCOLOR_XRGB(r, g, b));

        g_staticObjects.push_back(obj);
    }
    OutputDebugStringA("静态物体创建完成\n");

    // 创建10个运动障碍物（5个随机移动 + 5个往复平移）
    // 先将静态对象转换为GameObject*供碰撞检测用（使用全局向量保证生命周期）
    OutputDebugStringA("开始创建运动障碍物...\n");
    g_staticObjsForCollision.clear();
    for (size_t i = 0; i < g_staticObjects.size(); i++)
    {
        g_staticObjsForCollision.push_back(g_staticObjects[i]);
    }

    for (int i = 0; i < 10; i++)
    {
        MovingObstacle* movingObj = new MovingObstacle();

        // 前5个使用随机移动，后5个使用往复平移
        MovementType moveType = (i < 5) ? MOVEMENT_RANDOM : MOVEMENT_OSCILLATE;
        D3DXVECTOR3 size(8.0f, 8.0f, 8.0f);  // 运动障碍物统一使用立方体

        if (!movingObj->Initialize(g_pd3dDevice, moveType, size))
        {
            delete movingObj;
            continue;
        }

        // 随机初始位置
        float x = 100.0f + (rand() % 800);
        float z = 100.0f + (rand() % 800);
        float terrainHeight = g_pTerrain->GetHeight(x, z);
        float y = terrainHeight + size.y * 0.5f;  // 立方体底部贴地

        movingObj->SetPosition(D3DXVECTOR3(x, y, z));
        movingObj->SetMovementBounds(50.0f, 950.0f, 50.0f, 950.0f);
        movingObj->SetStaticObjects(&g_staticObjsForCollision);
        movingObj->SetTerrain(g_pTerrain);

        // 如果是往复运动，在SetPosition后初始化起点终点
        if (moveType == MOVEMENT_OSCILLATE)
        {
            movingObj->InitializeOscillateMovement();
        }

        g_movingObstacles.push_back(movingObj);
    }
    OutputDebugStringA("运动障碍物创建完成\n");

    // 设置光照
    SetupLighting();

    // 创建NPC管理器
    OutputDebugStringA("开始创建NPC管理器...\n");
    g_pNPCManager = new NPCManager();
    if (!g_pNPCManager->Initialize(g_pd3dDevice, 8, g_pTerrain))  // Max 8 NPCs (增加2个)
    {
        OutputDebugStringA("NPC管理器初始化失败！\n");
        return false;
    }
    OutputDebugStringA("NPC管理器创建成功\n");

    // Stage 3: 创建玩家坦克
    OutputDebugStringA("开始创建玩家坦克...\n");
    g_pPlayerTank = new PlayerTank();
    float playerX = 500.0f;
    float playerZ = 500.0f;
    float playerY = g_pTerrain->GetHeight(playerX, playerZ) + 2.5f;
    if (!g_pPlayerTank->Initialize(g_pd3dDevice, D3DXVECTOR3(playerX, playerY, playerZ)))
    {
        OutputDebugStringA("玩家坦克初始化失败！\n");
        return false;
    }
    g_pPlayerTank->SetTerrain(g_pTerrain);

    // 准备全局障碍物列表（静态+运动）供坦克碰撞检测
    g_allObstacles.clear();
    for (size_t i = 0; i < g_staticObjects.size(); i++)
    {
        g_allObstacles.push_back(g_staticObjects[i]);
    }
    for (size_t i = 0; i < g_movingObstacles.size(); i++)
    {
        g_allObstacles.push_back(g_movingObstacles[i]);
    }
    g_pPlayerTank->SetObstacles(&g_allObstacles);
    OutputDebugStringA("玩家坦克创建成功\n");

    // 设置相机跟随模式
    g_pCamera->SetFollowMode(true);

    // 创建UI渲染器
    OutputDebugStringA("开始创建UI渲染器...\n");
    g_pUIRenderer = new UIRenderer();
    if (!g_pUIRenderer->Initialize(g_pd3dDevice, SCREEN_WIDTH, SCREEN_HEIGHT))
    {
        OutputDebugStringA("UI渲染器初始化失败！\n");
        return false;
    }
    OutputDebugStringA("UI渲染器创建成功\n");

    return true;
}

// 设置光照
void SetupLighting()
{
    // 设置有色环境光（红绿混合）- 修改为符合需求
    g_pd3dDevice->SetRenderState(D3DRS_AMBIENT, D3DCOLOR_XRGB(100, 80, 0));  // 红绿混合色

    // 添加方向光
    D3DLIGHT9 light = {};
    light.Type = D3DLIGHT_DIRECTIONAL;
    light.Diffuse.r = 1.0f;
    light.Diffuse.g = 1.0f;
    light.Diffuse.b = 1.0f;
    light.Diffuse.a = 1.0f;

    D3DXVECTOR3 direction(-1.0f, -1.0f, 1.0f);
    D3DXVec3Normalize((D3DXVECTOR3*)&light.Direction, &direction);

    g_pd3dDevice->SetLight(0, &light);
    g_pd3dDevice->LightEnable(0, TRUE);
}

// 更新玩家坦克聚光灯
void UpdateSpotlight()
{
    if (!g_pPlayerTank || g_pPlayerTank->IsDead())
    {
        g_pd3dDevice->LightEnable(1, FALSE);
        return;
    }

    D3DLIGHT9 spotlight = {};
    spotlight.Type = D3DLIGHT_SPOT;

    // 纯绿色聚光灯（与红绿混合环境光区分）
    spotlight.Diffuse.r = 0.0f;
    spotlight.Diffuse.g = 1.0f;
    spotlight.Diffuse.b = 0.0f;
    spotlight.Diffuse.a = 1.0f;

    spotlight.Ambient.r = 0.0f;
    spotlight.Ambient.g = 0.3f;
    spotlight.Ambient.b = 0.0f;
    spotlight.Ambient.a = 1.0f;

    // 聚光灯位置（炮管位置）
    D3DXVECTOR3 gunPos = g_pPlayerTank->GetGunPosition();
    spotlight.Position = gunPos;

    // 聚光灯方向（炮管指向）
    D3DXVECTOR3 gunDir = g_pPlayerTank->GetGunDirection();
    spotlight.Direction = gunDir;

    // 聚光灯参数
    spotlight.Range = 200.0f;
    spotlight.Falloff = 1.0f;
    spotlight.Attenuation0 = 0.0f;
    spotlight.Attenuation1 = 0.01f;
    spotlight.Attenuation2 = 0.0f;
    spotlight.Theta = D3DX_PI / 8.0f;   // Inner cone: 22.5 degrees
    spotlight.Phi = D3DX_PI / 4.0f;     // Outer cone: 45 degrees

    g_pd3dDevice->SetLight(1, &spotlight);
    g_pd3dDevice->LightEnable(1, TRUE);
}

// 清理D3D
void CleanupD3D()
{
    if (g_pd3dDevice)
    {
        g_pd3dDevice->Release();
        g_pd3dDevice = NULL;
    }
    if (g_pD3D)
    {
        g_pD3D->Release();
        g_pD3D = NULL;
    }
}

// 清理游戏对象
void CleanupGame()
{
    // 清理静态物体
    for (size_t i = 0; i < g_staticObjects.size(); i++)
    {
        g_staticObjects[i]->Cleanup();
        delete g_staticObjects[i];
    }
    g_staticObjects.clear();
    g_staticObjsForCollision.clear();  // 清理碰撞检测用的向量

    // 清理运动障碍物
    for (size_t i = 0; i < g_movingObstacles.size(); i++)
    {
        g_movingObstacles[i]->Cleanup();
        delete g_movingObstacles[i];
    }
    g_movingObstacles.clear();

    // 清理地形
    if (g_pTerrain)
    {
        g_pTerrain->Cleanup();
        delete g_pTerrain;
        g_pTerrain = NULL;
    }

    // 清理相机
    if (g_pCamera)
    {
        delete g_pCamera;
        g_pCamera = NULL;
    }

    // 清理NPC管理器
    if (g_pNPCManager)
    {
        g_pNPCManager->Cleanup();
        delete g_pNPCManager;
        g_pNPCManager = NULL;
    }

    // 清理玩家坦克
    if (g_pPlayerTank)
    {
        g_pPlayerTank->Cleanup();
        delete g_pPlayerTank;
        g_pPlayerTank = NULL;
    }

    // 清理炮弹
    for (size_t i = 0; i < g_projectiles.size(); i++)
    {
        g_projectiles[i]->Cleanup();
        delete g_projectiles[i];
    }
    g_projectiles.clear();

    // 清理UI渲染器
    if (g_pUIRenderer)
    {
        g_pUIRenderer->Cleanup();
        delete g_pUIRenderer;
        g_pUIRenderer = NULL;
    }
}

// 更新游戏逻辑
void Update(float deltaTime)
{
    // 更新玩家坦克
    if (g_pPlayerTank && !g_pPlayerTank->IsDead())
    {
        g_pPlayerTank->Update(deltaTime);

        // 检查玩家是否开火
        static bool wasShootingLastFrame = false;
        bool isShooting = (GetAsyncKeyState(VK_SPACE) & 0x8000) || (GetAsyncKeyState(VK_LBUTTON) & 0x8000);

        if (isShooting && !wasShootingLastFrame)
        {
            // 创建炮弹
            Projectile* proj = new Projectile();
            D3DXVECTOR3 gunPos = g_pPlayerTank->GetGunPosition();
            D3DXVECTOR3 gunDir = g_pPlayerTank->GetGunDirection();

            if (proj->Initialize(g_pd3dDevice, gunPos, gunDir, 100.0f))
            {
                proj->SetTerrain(g_pTerrain);
                g_projectiles.push_back(proj);
            }
            else
            {
                delete proj;
            }
        }
        wasShootingLastFrame = isShooting;
    }

    // 更新炮弹
    for (size_t i = 0; i < g_projectiles.size();)
    {
        g_projectiles[i]->Update(deltaTime);

        // 移除非活跃炮弹
        if (!g_projectiles[i]->IsActive())
        {
            g_projectiles[i]->Cleanup();
            delete g_projectiles[i];
            g_projectiles.erase(g_projectiles.begin() + i);
            continue;
        }

        // 检查炮弹与NPC碰撞
        bool hit = false;
        if (g_pNPCManager)
        {
            std::vector<NPC*>& npcs = g_pNPCManager->GetNPCs();
            for (size_t j = 0; j < npcs.size(); j++)
            {
                if (!npcs[j]->IsDead() && g_projectiles[i]->CheckCollision(*npcs[j]))
                {
                    npcs[j]->TakeDamage(g_projectiles[i]->GetDamage());
                    hit = true;
                    break;
                }
            }
        }

        // 检查炮弹与障碍物碰撞
        if (!hit)
        {
            for (size_t j = 0; j < g_staticObjects.size(); j++)
            {
                if (g_projectiles[i]->CheckCollision(*g_staticObjects[j]))
                {
                    hit = true;
                    break;
                }
            }
        }

        if (!hit)
        {
            for (size_t j = 0; j < g_movingObstacles.size(); j++)
            {
                if (g_projectiles[i]->CheckCollision(*g_movingObstacles[j]))
                {
                    hit = true;
                    break;
                }
            }
        }

        if (hit)
        {
            g_projectiles[i]->Deactivate();
        }

        i++;
    }

    // 更新运动障碍物
    for (size_t i = 0; i < g_movingObstacles.size(); i++)
    {
        g_movingObstacles[i]->Update(deltaTime);
    }

    // Update NPCs
    if (g_pNPCManager && g_pPlayerTank)
    {
        std::vector<GameObject*> obstacles;
        for (size_t i = 0; i < g_staticObjects.size(); i++)
        {
            obstacles.push_back(g_staticObjects[i]);
        }
        for (size_t i = 0; i < g_movingObstacles.size(); i++)
        {
            obstacles.push_back(g_movingObstacles[i]);
        }
        g_pNPCManager->Update(deltaTime, g_pPlayerTank, obstacles);

        // NPC攻击玩家
        std::vector<NPC*>& npcs = g_pNPCManager->GetNPCs();
        for (size_t i = 0; i < npcs.size(); i++)
        {
            if (npcs[i]->GetState() == NPC_STATE_ATTACK)
            {
                // 使用距离判断而非包围盒碰撞
                D3DXVECTOR3 diff = npcs[i]->GetPosition() - g_pPlayerTank->GetPosition();
                float distance = D3DXVec3Length(&diff);

                // NPC 攻击范围内持续造成伤害
                if (distance < npcs[i]->GetAttackRange())
                {
                    float damageTaken = 10.0f * deltaTime;  // 每秒 10 点伤害
                    g_pPlayerTank->TakeDamage(damageTaken);

                    // Show damage indicator
                    g_damageIndicatorIntensity = 0.8f;
                }
            }
        }
    }

    // 更新相机跟随玩家坦克
    if (g_pCamera && g_pPlayerTank && !g_pPlayerTank->IsDead())
    {
        g_pCamera->FollowTarget(
            g_pPlayerTank->GetPosition(),
            g_pPlayerTank->GetRotation().y,
            g_pPlayerTank->GetTurretYaw(),
            deltaTime
        );
    }

    // 更新聚光灯
    UpdateSpotlight();

    // 更新受伤指示器（渐变消失）
    if (g_damageIndicatorIntensity > 0.0f)
    {
        g_damageIndicatorIntensity -= deltaTime * 2.0f;  // Fade out over 0.5 seconds
        if (g_damageIndicatorIntensity < 0.0f)
            g_damageIndicatorIntensity = 0.0f;
    }
}

// 渲染场景
void Render()
{
    if (!g_pd3dDevice)
        return;

    // 更新相机矩阵
    if (g_pCamera)
        g_pCamera->UpdateMatrices(g_pd3dDevice);

    // 清空缓冲区
    g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
        D3DCOLOR_XRGB(135, 206, 235), 1.0f, 0);  // 天蓝色

    // 开始渲染
    if (SUCCEEDED(g_pd3dDevice->BeginScene()))
    {
        // 渲染地形
        if (g_pTerrain)
            g_pTerrain->Render(g_pd3dDevice);

        // 渲染静态物体
        for (size_t i = 0; i < g_staticObjects.size(); i++)
        {
            g_staticObjects[i]->Render(g_pd3dDevice);
        }

        // 渲染运动障碍物
        for (size_t i = 0; i < g_movingObstacles.size(); i++)
        {
            g_movingObstacles[i]->Render(g_pd3dDevice);
        }

        // 渲染NPCs
        if (g_pNPCManager)
            g_pNPCManager->RenderAll(g_pd3dDevice);

        // 渲染玩家坦克
        if (g_pPlayerTank)
            g_pPlayerTank->Render(g_pd3dDevice);

        // 渲染炮弹
        for (size_t i = 0; i < g_projectiles.size(); i++)
        {
            g_projectiles[i]->Render(g_pd3dDevice);
        }

        // ========== 渲染UI（2D覆盖层） ==========
        if (g_pUIRenderer && g_pPlayerTank)
        {
            // 禁用深度测试和光照，启用Alpha混合
            g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
            g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
            g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
            g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
            g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

            // 渲染准星（屏幕中心十字）
            g_pUIRenderer->RenderCrosshair(g_pd3dDevice);

            // 渲染生命条（屏幕左下角）
            if (!g_pPlayerTank->IsDead())
            {
                g_pUIRenderer->RenderHealthBar(g_pd3dDevice,
                    g_pPlayerTank->GetHealth(),
                    g_pPlayerTank->GetMaxHealth(),
                    20.0f,  // x
                    (float)SCREEN_HEIGHT - 50.0f,  // y (bottom of screen - 50)
                    200.0f,  // width
                    20.0f);  // height
            }

            // 渲染受伤指示器（红色屏幕边缘闪烁）
            if (g_damageIndicatorIntensity > 0.0f)
            {
                g_pUIRenderer->RenderDamageIndicator(g_pd3dDevice, g_damageIndicatorIntensity);
            }

            // 恢复渲染状态
            g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
            g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE);
            g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
        }

        // 更新窗口标题（显示游戏状态 + 调试信息）
        if (g_pPlayerTank && !g_pPlayerTank->IsDead())
        {
            wchar_t title[256];
            int aliveNPCs = g_pNPCManager ? g_pNPCManager->GetAliveNPCCount() : 0;
            int totalNPCs = g_pNPCManager ? (int)g_pNPCManager->GetNPCs().size() : 0;

            // 统计 NPC 状态
            int chasing = 0, attacking = 0, patrolling = 0;
            if (g_pNPCManager)
            {
                std::vector<NPC*>& npcs = g_pNPCManager->GetNPCs();
                for (size_t i = 0; i < npcs.size(); i++)
                {
                    if (!npcs[i]->IsDead())
                    {
                        if (npcs[i]->GetState() == NPC_STATE_CHASE) chasing++;
                        else if (npcs[i]->GetState() == NPC_STATE_ATTACK) attacking++;
                        else if (npcs[i]->GetState() == NPC_STATE_PATROL) patrolling++;
                    }
                }
            }

            swprintf_s(title, L"DX9 Tank - HP: %.0f/%.0f | NPCs: %d/%d (P:%d C:%d A:%d)",
                g_pPlayerTank->GetHealth(),
                g_pPlayerTank->GetMaxHealth(),
                aliveNPCs, totalNPCs,
                patrolling, chasing, attacking);
            SetWindowText(g_hWnd, title);
        }
        else if (g_pPlayerTank && g_pPlayerTank->IsDead())
        {
            SetWindowText(g_hWnd, L"DX9 Tank Game - Stage 3 | YOU DIED!");
        }

        g_pd3dDevice->EndScene();
    }

    // 显示渲染结果
    g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
}

// WinMain入口
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
    // 注册窗口类
    WNDCLASSEX wc = {};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = L"DX9TankGame";

    RegisterClassEx(&wc);

    // 创建窗口
    g_hWnd = CreateWindow(
        L"DX9TankGame",
        L"DX9 Tank Game - Stage 3",
        WS_OVERLAPPEDWINDOW,
        100, 100,
        SCREEN_WIDTH, SCREEN_HEIGHT,
        NULL, NULL, hInstance, NULL
    );

    if (!g_hWnd)
        return 0;

    // 初始化D3D
    if (!InitD3D(g_hWnd))
    {
        MessageBox(NULL, L"初始化DirectX 9失败！", L"错误", MB_OK);
        return 0;
    }

    // 初始化游戏
    if (!InitGame())
    {
        MessageBox(NULL, L"初始化游戏失败！", L"错误", MB_OK);
        CleanupD3D();
        return 0;
    }

    ShowWindow(g_hWnd, nCmdShow);
    UpdateWindow(g_hWnd);

    // 主循环
    MSG msg = {};
    LARGE_INTEGER frequency, lastTime, currentTime;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&lastTime);

    while (msg.message != WM_QUIT)
    {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {
            // 计算deltaTime
            QueryPerformanceCounter(&currentTime);
            float deltaTime = (float)(currentTime.QuadPart - lastTime.QuadPart) / frequency.QuadPart;
            lastTime = currentTime;

            // 更新和渲染
            Update(deltaTime);
            Render();
        }
    }

    // 清理
    CleanupGame();
    CleanupD3D();

    return (int)msg.wParam;
}
